{layout name="common/base" }
<link rel="stylesheet" href="__PUBLIC__/css/goods.css">
<link rel="stylesheet" href="__PUBLIC__/css/sku_style.css"/>
<script type="text/javascript" src="__PUBLIC__/js/sku/createSkuTable.js?v20"></script>
<script src="__PUBLIC__/js/goods.js?c9"></script>
<script src="__PUBLIC__/js/common.js?b41"></script>
<input type="hidden" id="imagesArr">
<div class="layuimini-container">
    <form action="" class="layui-form" id="myform" lay-filter="form-filter">
        <input type="text" style="display: none;" value="{$data.id}" name="id">
        <div class="layuimini-main">
            <div class="layui-tab layui-tab-brief" lay-filter="docDemoTabBrief">
                <ul class="layui-tab-title">
                    <li class="layui-this">基本信息</li>
                    <li>商品规格</li>
                    <li>商品描述</li>
                    <!--<li>商品详情</li>-->
                </ul>
                <div class="layui-tab-content">
                    <!--基本信息 start-->
                    <div class="layui-tab-item layui-show">
                        <!--<input type="text" style="display: none;" value="0" name="is_score" title="普通商品">-->
                        <div class="layui-form-item">
                            <label class=" layui-form layui-form-label">商品名称</label>
                            <div class="layui-input-inline">
                                <input type="text" name="name" lay-verify="required" value="{$data.name}" placeholder="请输入商品名称" autocomplete="off" class="layui-input">
                            </div>
                        </div>

                        <div class="layui-form-item">
                            <label class="layui-form-label required">商品分类</label>
                            <div class="layui-input-inline">
                                <select name="category_id">
                                    <?php foreach ($parentData as $k => $v): ?>
                                    <option <?php if($v['id'] == $data['category_id']): ?>selected="selected"<?php endif; ?> value="<?php echo $v['id']; ?>"><?php echo str_repeat('-', 4*$v['level']).$v['name']; ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>

                        <div class="layui-form layui-form-item">
                            <label class="layui-form-label">商品单位</label>
                            <div class="layui-input-inline">
                                <input type="text" name="unit_name" id="goods_unit" value="{$data.unit_name}" placeholder="请输入商品单位" autocomplete="off" class="layui-input">
                            </div>
                        </div>

                        <div class="layui-form-item">
                            <label class="layui-form-label">商品图</label>
                            <div class="layui-input-block">
                                <button type="button" class="layui-btn" id="upload_btn">
                                    <i class="layui-icon">&#xe67c;</i>上传图片
                                </button>
                                <div><tip>上传图片正方形1张</tip></div>
                                <img id="previewImg" width="60px" height="60px" onclick="showimg(this)" src="<?php echo config('setting.domain_prefix').config('setting.image_prefix').$data['image'];?>">
                                <input id="upload_image" name="image" type="hidden" multiple="true" value="{$data.image}">
                            </div>
                        </div>

                        <div class="layui-form-item">
                            <label class="layui-form-label">上传轮播图</label>
                            <div class="layui-input-block">
                                <input type="hidden" name="carousel_image" class="multiple_show_img" value="{$data.carousel_image}">
                                <button type="button" class="layui-btn" id="upload_btn_more">
                                    <i class="layui-icon">&#xe67c;</i>多图片上传
                                </button>
                                <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;">
                                    预览图：
                                    <div class="layui-upload-list" id="div_slide_show">
                                        {if condition="count($carousel_image_arr) > 0"}
                                        <?php foreach($carousel_image_arr as $k=>$v):?>
                                        <img style="width:60px;height:60px;" src="<?php echo config('setting.domain_prefix').config('setting.image_prefix');?>{$v}" title="点击删除" class="layui-upload-img" onclick="delMultipleImgs(this)">
                                        <?php endforeach;?>
                                        {/if}
                                    </div>
                                </blockquote>

                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label required">热门</label>
                            <div class="layui-input-block">
                                <input type="radio" name="is_hot" value="0" title="否" <?php if($data['is_hot'] == 0) echo 'checked="checked"';?> >
                                <input type="radio" name="is_hot" value="1" title="是" <?php if($data['is_hot'] == 1) echo 'checked="checked"';?> >
                            </div>
                        </div>

                        <div class="layui-form-item">
                            <label class="layui-form-label required">状态</label>
                            <div class="layui-input-block">
                                <input type="radio" name="status" title="下架" <?php if($data['status'] == 0) echo 'checked="checked"';?> value='0'/>
                                <input type="radio" name="status" title="上架" <?php if($data['status'] == 1) echo 'checked="checked"';?> value='1'/>
                            </div>
                        </div>

                        <div class="layui-form-item">
                            <label class="layui-form-label">排序</label>
                            <div class="layui-input-block" style="width:375px;">
                                <input type="number" name="sort" placeholder="请输入排序" value="<?php echo $data['sort'];?>" class="layui-input">
                                <tip>只能输入数字!</tip>
                            </div>
                        </div>

                        <div class="layui-form layui-form-item">
                            <label class="layui-form-label">虚拟销量</label>
                            <div class="layui-input-inline">
                                <input type="text" name="fake_sales" id="fake_sales" placeholder="请输入商品销量" value="<?php echo $data['fake_sales'];?>" autocomplete="off" class="layui-input">
                                <tip>前端展示!</tip>
                            </div>
                        </div>

                    </div>
                    <!--基本信息 end-->

                    <div class="layui-tab-item">
                        <div class="layui-form layui-form-item">
                            <label class="layui-form-label">商品规格</label>
                            <div class="layui-input-block">
                                <input type="radio" name="specs_type" lay-filter="spec" value="1" title="统一规格" <?php if($data['specs_type'] == 1) echo 'checked="checked"';?>>
                                <input type="radio" name="specs_type" lay-filter="spec" value="2" title="多规格" <?php if($data['specs_type'] == 2) echo 'checked="checked"';?>>
                            </div>
                        </div>
                        <div class="layui-form-item spec-more" style="display: none">
                            <label class="layui-form-label"></label>
                            <div class="layui-input-block  spec-more-block">
                                <table class="layui-table">
                                    <colgroup>
                                        <col width="500">
                                    </colgroup>
                                    <thead>
                                    <tr>
                                        <th>规格值</th>
                                    </tr>
                                    </thead>
                                    <tbody class="spec-content">
                                    </tbody>
                                </table>
                                <div class="layui-btn-container">
                                    <button type="button" class="layui-btn add-spec">添加规格</button>
                                </div>

                                <!--生成 规格 start-->
                                <!--                                <div class="layui-tab-item">-->
                                <div class="control-group choose_config">
                                    <div class="skus-warp"></div>
                                    <div class="clear"></div>
                                    <div id="skuTable">
                                        <table class="skuTable">
                                            <tbody>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                            <!--生成 规格 end-->
                        </div>

                        <div class="layui-form-item spec-is-show">
                            <label class="layui-form-label">市场价格</label>
                            <div class="layui-input-inline">
                                <input type="text" name="market_price" id="market_price" value="{$data.market_price}" placeholder="请输入市场价 /元"
                                       autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-form-item spec-is-show">
                            <label class="layui-form-label">销售价</label>
                            <div class="layui-input-inline">
                                <input type="text" name="sell_price" id="sell_price" value="{$data.sell_price}" placeholder="请输入销售价 /元" autocomplete="off" class="layui-input">
                            </div>
                        </div>

                        <div class="layui-form-item spec-is-show">
                            <label class="layui-form-label">总库存</label>
                            <div class="layui-input-inline">
                                <input type="number" name="stock" id="goods_stock" value="{$data.stock}" placeholder="请输入商品总库存 /件" autocomplete="off" class="layui-input">
                            </div>
                        </div>

                    </div>

                    <div class="layui-tab-item">
                        <div class="layui-form-item">
                            <label class=" layui-form layui-form-label">商品描述</label>
                            <div class="layui-input-inline" style="width:750px;">
                                <textarea id="editor" style="display: none;">{$data.content}</textarea>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="layui-form-item layui-form">
            <div class="layui-input-block">
                <!--<button class="layui-btn" lay-submit lay-filter="saveBtn">确认保存</button>-->
                <!--<button type="submit" class="layui-btn" id='btnSubmit' lay-submit="" lay-filter="goods_submit">立即提交</button>-->
                <button type="submit" class="layui-btn" id='btnSubmit' lay-submit="" lay-filter="*">立即提交</button>
            </div>
        </div>
        <div>{:token()}</div>
    </form>
</div>

<script>
    //多图容器 【注册全局变量】
    var multiple_images = [];

    layui.use(['form', 'layedit', 'laydate', 'element','upload'], function () {
        var form = layui.form
            , layer = layui.layer
            , layedit = layui.layedit
            , $ = layui.$
            , upload = layui.upload; //Tab的切换功能，切换事件监听等，需要依赖element模块

        layedit.set({
            uploadImage: {
                url: "/admin/image/layUploadNo",
                type: 'post'
            }
        });

        var edit_content = layedit.build('editor'); //建立编辑器

        form.on('radio(spec)', function (data) {
            // 多规格处理
            $('.spec-more').css('display', (data.value == 2 ? 'block' : 'none'));
            $('.spec-is-show').css('display', (data.value == 1 ? 'block' : 'none'));
        });

        var spec_index = $('.spec-content').children('tr').length;
        $('.add-spec').on('click', function () {
            spec_index++;
            var html = `<tr class="tr${spec_index}">
                            <td>
                            <div class="layui-form-item">
                            <div class="layui-input-inline" style="width:  600px">
                            <input type="text" name="spec_group[]" placeholder="请输入规格名" autocomplete="off" class="layui-input">
                            <ul style="margin-top: 12px"></ul>
                            </div>
                            <div class="layui-form-mid layui-word-aux">
                            <i class="layui-icon add-spec-btn" style="margin-left: 10px;cursor:pointer;">&#xe65f;</i>
                            <i class="layui-icon del-spec" style="margin-left: 100px;cursor:pointer;">&#xe640;</i>
                            </div>
                            </div>
                            </td>
                        </tr>`;
            $('.spec-content').append(html)
        });

        // 显示规格页面
        $('body').on('click', '.add-spec-btn', function () {
            var cls = $(this).parent().parent().parent().parent().attr('class');
            console.log(cls);
            layObj.dialog("/admin/store.specs/dialog?cls="+cls, '添加规格')
        });

        // 显示规格  输入框
        var specs_type = '{$data.specs_type}';
        if(parseInt(specs_type) == 2){

            var objEditArr = '{$data.goods_specs_data}';

            var objEdit = JSON.parse(objEditArr);
            form.val('form-filter',objEdit);
            $('.spec-more').css('display', (objEdit.spec == 2 ? 'block' : 'none'));
            $('.spec-is-show').css('display', (objEdit.spec == 1 ? 'block' : 'none'));
            if(objEdit.spec == 2){
                skustab(objEdit.add_spec_arr)
                skusData(objEdit.skus)
                form.render();
            }

            // 删除规格输入框
            $('body').on('click', '.del-spec', function () {
                var trs = $(this).parent().parent().parent().parent();//
                trs.remove();//删除tr
                var el = trs.attr('class');
                $('.del-' + el).remove();

                // 删除规格复选框栏
                var input_id =  $(this).parent().prev().find('input').attr('data-id');

                $("ul[class*='SKU_TYPE']").each(function (i, item) {
                    var propid = $(this).find('li').attr('propid');
                    if(propid == input_id){
                        $(this).next().next().remove();
                        $(this).next().remove();
                        $(this).remove();
                        return false;
                    }
                });
                // 规格赋值
                getAlreadySetSkuVals();
                // 创建表格
                createTab();
                var spec_len = $('.spec-content').children('tr').length;
                if(spec_len == 0){
                    $("#skuTable").html('<table class="skuTable"><tbody></tbody></table>');
                }

            });

        }

        /*$("#btnSubmit").on("click", function () {
            $(".buttons").click();
        });*/
        layui.form.on('submit(*)', function (data) {
            var goods_data = {
                    ...data.field,
                skus: skus1(),
                content: layedit.getContent(edit_content),
                add_spec_arr: addSpecArr() // 提交的规格数据
            }
            console.log(goods_data);//这个data就是表单的值 包含以下值
            var url = '/admin/store.goods/edit';
            // 发送ajax请求
            layObj.post(url, goods_data,  (res) =>{
                    layer.msg(res.msg, {
                    icon: 1,
                    time: 2000 //2秒关闭（如果不配置，默认是3秒）
                }, function(){
                    console.log(res);
                    if(res.code == 1){
                        // 关闭弹出层
                        var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
                        parent.location.reload();//刷新父页面，注意一定要在关闭当前iframe层之前执行刷新
                        parent.layer.close(index); //再执行关闭
                    }else{

                    }
                });
            });

            return false;

            image_upload();
        });


        /*if(parseInt(specs_type) == 2){
            var objEditArr = '{$data.goods_specs_data}';

            var objEdit = JSON.parse(objEditArr);
            form.val('form-filter',objEdit);

            $('.spec-more').css('display', (objEdit.spec == 2 ? 'block' : 'none'));
            $('.spec-is-show').css('display', (objEdit.spec == 1 ? 'block' : 'none'));
            if(objEdit.spec == 2){
                skustab(objEdit.add_spec_arr)
                skusData(objEdit.skus)
                form.render();
            }
        }*/

    });

    // 提交的规格数据
    function addSpecArr() {
        // 规格值 数组
        var specArr = [];
        $("input[name^='spec_group']").each(function (i, el) {
            var that = $(this)
                , lis = that.next().children('li')
                , eleLi = ''
                , project = [];

            lis.each(function (index, item) {
                var propvalid = $(item).attr('propvalid');// 31,13,22
                //eleLi += $(item).text() + ','
                var name = $(item).text();
                var obja = {
                    specs_value_id: propvalid,
                    name: name
                };
                project.push(obja);
            });
            var id = that.attr('data-id'),
                name = that.attr('data-name');
            //project = eleLi.slice(0, -1);
            //console.log(lis);
            specArr.push({id, name, project})
        });
        console.log(specArr);
        return specArr
    }

    // 修改时创建数据
    function skustab(moke) {
        console.log(moke)
        let pli = ''// 选择框栏 tr
            , child_li = ''// 选择框 li 栏
            , tmp = '' // 是复选框栏
            ,trindex = 0
        for (let item of moke) {
            console.log(item.project)
            trindex++;
            tmp += `<ul class="SKU_TYPE" >
                                    <li is_required='1' propid='${item.id}' sku-type-name="${item.name}"><em>*</em>${item.name}</li>
                                </ul>
                                <ul>`;
            //let projectArr = item.project.split(',');
            //console.log(projectArr)
            let projectArr = item.project;

            projectArr.forEach(function (item1,index1,arr1) {
                tmp += `<li><label><input type="checkbox"  class="sku_value" style="display:block;" lay-ignore  propvalid="${item1.specs_value_id}" value="${item1.name}"/>${item1.name}</label></li>`;
                child_li += `<li class="layui-badge layui-bg-blue" propvalid="${item1.specs_value_id}">${item1.name}</li>`
            })
            /*for(var i=0;i<=projectArr.length;i++){
                console.log(phone[i])
            }*/

            tmp += `</ul><div class="clear"></div>`

            pli += `<tr class="tr${trindex}">
                                        <td>
                                            <div class="layui-form-item">
                                                <div class="layui-input-inline" style="width:  600px">
                                                    <input type="text" name="spec_group[]" lay-verify="required" placeholder="请输入规格名" autocomplete="off"  value="${item.name}" class="layui-input" data-id="${item.id}" data-name="规格">
                                                           <ul style="margin-top: 12px">
                                                           ${child_li}
                                                           </ul>
                                                </div>
                                                <div class="layui-form-mid layui-word-aux">
                                                    <i class="layui-icon add-spec-btn" style="margin-left: 10px;cursor:pointer;"></i>
                                                    <i class="layui-icon del-spec" style="margin-left: 100px;cursor:pointer;"></i>
                                                </div>
                                            </div>
                                        </td>
                                    </tr>`
            child_li = ''
        }
        $('.spec-content').html(pli);
        $('.skus-warp').append(tmp)
    }

    function skusData(skus) {
        for (var item of skus) {
            var propvalids = item['propvalnames']['propvalids'].split(',')
            $(".sku_value").each(function (i, item) {
                let propvalid = $(this).attr('propvalid');
                if (propvalids.includes(propvalid)) {
                    $(this).attr('checked', true);
                }
            })
            alreadySetSkuVals[item['propvalnames']['propvalids']] = {
                "sell_price": item['propvalnames']['skuSellPrice'],
                "market_price": item['propvalnames']['skuMarketPrice'],
                "stock": item['propvalnames']['skuStock']
            }
        }
        // 创建 规格表格
        createTab()
    }

    //单击图片删除图片 【注册全局函数】
    function delMultipleImgs(this_img){
        //获取下标
        var subscript=$("#div_slide_show img").index(this_img);
        //删除图片
        this_img.remove();
        //删除数组
        multiple_images.splice(subscript, 1);
        //重新排序
        multiple_images.sort();
        //$('.multiple_show_img').val(multiple_images);
        $(".multiple_show_img").attr("value", multiple_images);
        //返回
        return ;
    }


    /*查看图片*/
    function showimg(url) {
        var img_infor = "<img src='" + url.src + "'  width='750' height='600' />";
        layer.open({
            type: 1,
            closeBtn: 1,
            shade: false,
            title: false, //不显示标题
            skin: 'layui-layer-nobg', //没有背景色
            shadeClose: false,
            area:['750px','600px'],
            content: img_infor //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响

        });
    }
</script>

